package com.kingdee.eas.hr.emp.app;

import java.sql.SQLException;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.emp.PersonWorkExpInfo;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;

public class PersonWorkExpControllerBeanEx extends PersonWorkExpControllerBean {

	@Override
	protected IObjectPK _addnew(Context ctx, IObjectValue model) throws BOSException, EASBizException {
		IObjectPK pk = super._addnew(ctx, model);
		PersonWorkExpInfo personWorkExpInfo = (PersonWorkExpInfo) model;
		this.updatePersonInfo(ctx, personWorkExpInfo);
		return pk;
	}

	@Override
	protected void _update(Context ctx, IObjectPK pk, IObjectValue model) throws BOSException, EASBizException {
		super._update(ctx, pk, model);
		PersonWorkExpInfo personWorkExpInfo = (PersonWorkExpInfo) model;
		this.updatePersonInfo(ctx, personWorkExpInfo);
	}

	@Override
	protected void _delete(Context ctx, IObjectPK pk) throws BOSException, EASBizException {
		super._delete(ctx, pk);
		PersonWorkExpInfo personWorkExpInfo = this.getPersonWorkExpInfo(ctx, pk);
		this.updatePersonInfo(ctx, personWorkExpInfo);
	}

	private void updatePersonInfo(Context ctx, PersonWorkExpInfo personWorkExpInfo) throws EASBizException,
			BOSException {
		try {

			PersonInfo personInfo = personWorkExpInfo.getPerson();
			personInfo = PersonFactory.getLocalInstance(ctx).getPersonInfo(new ObjectUuidPK(personInfo.getId()));

			IRowSet rs = DbUtil.executeQuery(ctx,
					"SELECT MIN(T.FBEGINDATE) FROM T_HR_PERSONWORKEXP T GROUP BY T.FPERSONID HAVING T.FPERSONID='"
							+ personInfo.getId() + "'");
			if (rs.next()) {
				personInfo.setJoinWorkDate(rs.getDate(1));
			} else {
				personInfo.setJoinWorkDate(null);
			}
			rs = DbUtil
					.executeQuery(
							ctx,
							"SELECT FUNITNAME FROM T_HR_PERSONWORKEXP WHERE FENDDATE IN (SELECT MAX(FENDDATE) FROM T_HR_PERSONWORKEXP GROUP BY FPERSONID HAVING FPERSONID='"
									+ personInfo.getId() + "')");
			if (rs.next()) {
				personInfo.setOriginalUnit(rs.getString(1));
			} else {
				personInfo.setOriginalUnit(null);
			}

			PersonFactory.getLocalInstance(ctx).updatePartial(personInfo, getSelectorItemCollection());
		} catch (SQLException e) {
			throw new BOSException(e);
		}
	}

	private SelectorItemCollection getSelectorItemCollection() {
		SelectorItemCollection selectors = new SelectorItemCollection();
		selectors.add("joinWorkDate");
		selectors.add("originalUnit");
		return selectors;
	}
}
